from tkinter import Label
from typing import List, Optional
import traceback

from matplotlib import font_manager

from models import Student, Course, db, Major, Score, Resume
import matplotlib.pyplot as plt


# 个人情况查询
def get_message(stu_id):
    stu = Resume.query.filter(Resume.id == stu_id).first()
    try:
        resume = "学生姓名：" + stu.name + "\ngender" + stu.gender + "\n年龄：" + stu.age + "\n学制：" + stu.length_of_schooling + "\n地区：" + stu.region + "\n政治面貌：" + stu.political_affilliation + "\n奖惩：" + stu.reward_and_punishment + "\n休复转退" + stu.special
        return resume
    except Exception as e:
        return traceback.format_exc()


# 按照学生地区来源统计
def show_pie_by_region():
    def get_stus():
        cities = ['河北省', '山西省', '辽宁省', '吉林省', '黑龙江省', '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', '河南省', \
                  '湖北省', '湖南省', '广东省', '海南省', '四川省', '贵州省', '云南省', '陕西省', '甘肃省', '青海省', '台湾省', \
                  '内蒙古自治区', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区', '北京市', '天津市', '上海市', \
                  '重庆市', '香港特别行政区', '澳门特别行政区']

        resumes = Resume.query.all()
        for resume in resumes:
            if resume.region == "河北省":
                cities[0].append(resume)
            elif resume.region == "山西省":
                cities[1].append(resume)
            elif resume.region == "辽宁省":
                cities[2].append(resume)
            elif resume.region == "吉林省":
                cities[3].append(resume)
            elif resume.region == "黑龙江省":
                cities[4].append(resume)
            elif resume.region == "江苏省":
                cities[5].append(resume)
            elif resume.region == "浙江省":
                cities[6].append(resume)
            elif resume.region == "安徽省":
                cities[7].append(resume)
            elif resume.region == "福建省":
                cities[8].append(resume)
            elif resume.region == "江西省":
                cities[9].append(resume)
            elif resume.region == "山东省":
                cities[10].append(resume)
            elif resume.region == "河南省":
                cities[11].append(resume)
            elif resume.region == "湖北省":
                cities[12].append(resume)
            elif resume.region == "湖南省":
                cities[13].append(resume)
            elif resume.region == "广东省":
                cities[14].append(resume)
            elif resume.region == "海南省":
                cities[15].append(resume)
            elif resume.region == "四川省":
                cities[16].append(resume)
            elif resume.region == "贵州省":
                cities[17].append(resume)
            elif resume.region == "云南省":
                cities[18].append(resume)
            elif resume.region == "陕西省":
                cities[19].append(resume)
            elif resume.region == "甘肃省":
                cities[20].append(resume)
            elif resume.region == "青海省":
                cities[21].append(resume)
            elif resume.region == "台湾省":
                cities[22].append(resume)
            elif resume.region == "内蒙古自治区":
                cities[23].append(resume)
            elif resume.region == "广西壮族自治区":
                cities[24].append(resume)
            elif resume.region == "西藏自治区":
                cities[25].append(resume)
            elif resume.region == "宁夏回族自治区":
                cities[26].append(resume)
            elif resume.region == "新疆维吾尔自治区":
                cities[27].append(resume)
            elif resume.region == "北京市":
                cities[28].append(resume)
            elif resume.region == "天津市":
                cities[29].append(resume)
            elif resume.region == "上海市":
                cities[30].append(resume)
            elif resume.region == "重庆市":
                cities[31].append(resume)
            elif resume.region == "香港特别行政区":
                cities[32].append(resume)
            elif resume.region == "澳门特别行政区":
                cities[33].append(resume)
        return cities[0], cities[1], cities[2], cities[3], cities[4], cities[5], cities[6], cities[7], cities[8], \
               cities[9], cities[10], cities[11], cities[12], cities[13], cities[14], cities[15], cities[16], \
               cities[17], cities[18], cities[19], cities[20], cities[21], cities[22], cities[23], cities[24], \
               cities[25], cities[26], cities[27], cities[28], cities[29], cities[30], cities[31], cities[32], \
               cities[33]

    params = [len(s) for s in get_stus()]
    print(params)
    my_font = font_manager.FontProperties(fname="/System/Library/Fonts/PingFang.ttc")

    labels = '河北省', '山西省', '辽宁省', '吉林省', '黑龙江省', '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', '河南省', \
             '湖北省', '湖南省', '广东省', '海南省', '四川省', '贵州省', '云南省', '陕西省', '甘肃省', '青海省', '台湾省', \
             '内蒙古自治区', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区', '北京市', '天津市', '上海市', \
             '重庆市', '香港特别行政区', '澳门特别行政区'

    explode = (0, 0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
               0)  # only "explode" the 2nd slice (i.e. 'Hogs')

    fig1, ax1 = plt.subplots()
    ax1.pie(params, explode=explode, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=90, textprops={"fontproperties": my_font})
    ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

    plt.title("全校学生地区分布情况", fontproperties=my_font)

    plt.savefig("./by_region.png")


# 按照学生年龄大小人数统计
def show_pie_by_age():
    def get_stus():
        first = []
        second = []
        third = []
        forth = []
        fifth = []
        resumes = Resume.query.all()
        for resume in resumes:
            if resume.age > 23:
                fifth.append(resume)
            elif resume.age == 23:
                forth.append(resume)
            elif resume.age == 22:
                third.append(resume)
            elif resume.age == 21:
                second.append(resume)
            elif resume.age == 20:
                first.append(resume)
            return first, second, third, forth, fifth

    params: List[int] = [len(s) for s in get_stus()]
    my_font = font_manager.FontProperties(fname="/System/Library/Fonts/PingFang.ttc")

    labels = '20岁', '21岁', '22岁', '23', '23以上'

    explode = (0, 0.1, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

    fig1, ax1 = plt.subplots()
    ax1.pie(params, explode=explode, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=90, textprops={"fontproperties": my_font})
    ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

    plt.title("全校学生年龄分布情况", fontproperties=my_font)

    plt.savefig("./by_age.png")


# 绘制饼图统计某专业某年级某学期成绩
# 参数major为专业名，grade为年级， term为学期
def show_pie_by_score(major_name, grade, term):
    major_id = Major.query.filter(Major.major_name == major_name).first().id

    def get_score(major_id, grade, term):
        first = []
        second = []
        third = []
        forth = []
        fifth = []
        stus = Student.query.filter(
            Student.grade == grade and Student.major_id == major_id and Student.term == term).all()
        scores = []
        for stu in stus:
            for s in stu.scores:
                course = Course.query.get(s.course_id)
                if s.score < 60:
                    fifth.append(s.score)
                elif 59 < s.score < 70:
                    forth.append(s.score)
                elif 69 < s.score < 80:
                    third.append(s.score)
                elif 79 < s.score < 90:
                    second.append(s.score)
                elif 89 < s.score < 100:
                    first.append(s.score)
                return first, second, third, forth, fifth

    params = [len(s) for s in get_score(major_id, grade, term)]
    my_font = font_manager.FontProperties(fname="/System/Library/Fonts/PingFang.ttc")

    labels = '90~100', '80~89', '70~79', '60~69', '60以下'

    explode = (0, 0.1, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

    fig1, ax1 = plt.subplots()
    ax1.pie(params, explode=explode, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=90, textprops={"fontproperties": my_font})
    ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

    plt.title(Major.query.get(major_id).major_name + "专业" + grade + term + "成绩情况", fontproperties=my_font)

    plt.savefig("./by_score.png")


def addCourse(c_name):
    course = Course(course_name=c_name)
    db.session.add()
    db.session.commit()


def addMajor(id, m_name):
    major = Major(id=id, major_name=m_name)
    db.session.add(major)
    db.session.commit()


def addStu(s_id, name, major_id, gender, grade):
    try:
        stu = Student(id=s_id, name=name, major_id=major_id, gender=gender, grade=grade)
        db.session.add(stu)
        db.session.commit()
        return 1
    except Exception as e:
        print(e.__str__())
        return 0


def addScore(stu_id, c_name, term, score):
    co = Course.query.filter(Course.course_name == c_name).first()
    score = Score(student_id=stu_id, course_id=co.id, term=term, score=score)
    if score:
        db.session.add(score)
        db.session.commit()
        return score
    else:
        return 0


def updateStu(id, name, major_id, gender, grade):
    stu = Student.query.filter(Student.id == id)
    if stu:
        stu.update(
            {"name": name,
             "major_id": major_id,
             "gender": gender,
             "grade": grade}
        )
        db.session.commit()
        return stu
    else:
        return 0


def delStu(stu_id):
    stu = Student.query.get(stu_id)
    if stu:
        db.session.delete(stu)
        db.session.commit()
        return stu
    else:
        return 0


def addResume(s_id: int, name: str, length_of_schooling: str, region: str, age: int, political_affiliation: str,
              gender: str, reward_and_punishment: str,
              special: str) -> Optional[Resume]:
    resume = Resume(id=s_id, name=name, length_of_achooling=length_of_schooling, region=region, age=age,
                    political_affiliation=political_affiliation, gender=gender,
                    reward_and_punishment=reward_and_punishment,
                    special=special)
    if resume:
        db.session.add(resume)
        db.session.commit()
        return resume
    else:
        return None
